package com.itheima.sh.controller;


import com.itheima.sh.pojo.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;


import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("consumer")
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    DiscoveryClient discoveryClient;

    @GetMapping("{id}")
    @HystrixCommand(fallbackMethod = "querByIdFallBack")
    public User queryById (@PathVariable("id") String username){
//        String url = "http://localhost:8081/user/" + id;

//        List<ServiceInstance> instances= discoveryClient.getInstances("user-service");
//        ServiceInstance serviceInstance = instances.get(0);
//
//        String host = serviceInstance.getHost(); //获取端口主机地址
//        int port = serviceInstance.getPort();  //获取端口
//        String url = "http://"+host+":"+port+"/user/" + id;

        String url ="http://user-service/user/" + username; //user-service 微服务名称
        //测试熔断
        if ("itheima".equals(username)) {
            throw new RuntimeException("itheima");
        }

        User user = restTemplate.getForObject(url, User.class);
        System.out.println(user);
        return user;
    }

    //降级方法
    public User querByIdFallBack(String username){
        User user = new User();
        user.setUsername(username);
        user.setName("暂停服务");
        return user;
    }
}
